package com.example.demo.controller;

import com.example.demo.pojo.Dept;
import com.example.demo.service.DeptService;
import com.example.demo.utils.ZTreeUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/dept")
public class DeptController {

    @Resource
    private DeptService deptService;

    @RequestMapping("/list")
    public List<ZTreeUtil> DeptTree(String name){
        List<Dept> depts = deptService.selectAllDept(name);
        ArrayList<ZTreeUtil> list = new ArrayList<>();
        Map<String,ZTreeUtil> map = new HashMap<>(16);
        Set<BigDecimal> idList = new HashSet<>();
        Set<BigDecimal> parentList = new HashSet<>();
        for (Dept dept:depts) {
            ZTreeUtil zTree = new ZTreeUtil(dept.getId(), dept.getParentid(), dept.getName(),false);
            if (name != null && !"".equals(name)) {
                zTree.setOpen(true);
            }
            map.put(dept.getName(),zTree);
            parentList.add(dept.getId());
            idList.add(dept.getParentid());
        }
        //关联查询才需要查询对应上级机构和下级机构
        if (name != null && !"".equals(name)){
            //查询上级机构和下级机构
            List<Dept> linkDepts = deptService.selectLinkDeptByIds(idList,parentList);
            for (Dept dept:linkDepts) {
                ZTreeUtil zTree = new ZTreeUtil(dept.getId(), dept.getParentid(), dept.getName(),true);
                map.putIfAbsent(dept.getName(), zTree);
            }
        }
        for (String key: map.keySet()) {
            list.add(map.get(key));
        }
        return list;
    }

}
